#coding:utf-8
'''
Created on 2016年9月9日
公众统一平台授权SDK
@author: lanjinmin
'''
import urllib
import time
import hashlib
import requests
import json

APPID = "wx50efccba4c72e9f9"#"wxc277cec6a0f458d9"
APPSECRETT = "a03e2bd6e9f8dd9be35c95a6c01fd899"#"62939128422df8d799a4ffb833a45fda"
AUTH_URL = "https://auth.mp.henkuai.com/mp/auth"
AUTH_INFO_URL = "https://auth.mp.henkuai.com/v1/api/user/userinfo"
JSSDK_CONFIG_URL = "https://auth.mp.henkuai.com/v1/api/jssdk/jssdk_config"
API_HOST = "https://auth.mp.henkuai.com"

class AuthClient(object):
    
    def __init__(self, appid,appsecret):
        """公众统一平台授权SDK
        """
        self.appid = appid
        self.appsecret = appsecret
        
    @classmethod
    def dict_to_url(cls,props):
        """字典生成url的GET参数链接
        """
        parm_items = sorted(props.items(), key=lambda d: d[0])
        parmlist = ["%s=%s"%item for item in parm_items]
        return "&".join(parmlist)
    
    def get_sign(self,props,appsecret):
        """生成url参数加密信息
        """
        souce_str = self.dict_to_url(props)
        md = hashlib.md5()
        md.update(souce_str+"&key=%s"%appsecret)
        sign = md.hexdigest().upper()
        return sign
    
    def _request(self,url,params,method="GET",timeout=10):
        """请求
        """
        try:
            if method=="GET":
                r = requests.get(url,params = params,timeout=timeout)
            else:
                r = requests.post(url,data = params,timeout=timeout)
            return r.text
        except:
            return "{}"
        
    def api(self,path,params,method="GET",timeout=10):
        """api请求
        """
        url = "%s%s"%(API_HOST,path)
        return json.loads(self._request(url, params, method, timeout))
    
    
        
    def product_auth_url(self,url,scope="snsapi_userinfo"):
        url = urllib.quote(url)
        timestamp = str(int(time.time()))
        props = {"appid":self.appid,"bkurl":url,"scope":scope,"timestamp":timestamp}
        sign = self.get_sign(props, self.appsecret)
        redirect_url = "%s?appid=%s&bkurl=%s&scope=%s&timestamp=%s&sign=%s"%(AUTH_URL,
                                                self.appid,url,scope,timestamp,sign)
        return redirect_url
    
    def get_user_info(self,openid):
        """获取用户信息
        """
        params = {"appid":self.appid,"openid":openid}
        sign = self.get_sign(params, self.appsecret)
        params["sign"] = sign
        path = "/v1/api/user/userinfo"
        return self.api(path, params,method="POST")
    
    def get_jssdk_config(self,url):
        """获取用户信息
        """
        params = {"appid":self.appid,"url":url}
        sign = self.get_sign(params, self.appsecret)
        params["sign"] = sign
        path = "/v1/api/jssdk/jssdk_config"
        return self.api(path, params,method="POST")
    
    def push_message(self,openid,content):
        """推送消息
        """
        params = {"appid":self.appid,"openid":openid,"content":content}
        sign = self.get_sign(params, self.appsecret)
        params["sign"] = sign
        path = "/v1/api/msg/message_push"
        return self.api(path, params,method="POST")
    
    def check_auth_data(self,props,timeout=60):
        """检测授权信息
        """
        openid = props.get("openid")
        sign = props.pop("sign")
        timestamp = props.get("timestamp")
        if not openid or openid=="None":
            return False
        if not sign==self.get_sign(props, authclient.appsecret):
            return False
        if timestamp + timeout<time.time():
            return False
        return True
        
        
authclient = AuthClient(APPID,APPSECRETT)


if __name__=="__main__":
#     print authclient.push_message("oWIm8s9yaDDNV_AQoAyyz9iVNpug", "123111")
    print authclient.product_auth_url("http://www.baidu.com")